<?php

namespace app\admin\controller;

use app\BaseController;
use app\service\category\CategoryLogic;

class Category extends BaseController
{
    public function index()
    {
        $arrList = CategoryLogic::getInstance()->getList();
        return view('', ['arrList' => $arrList]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $arrParam = $this->request->all();
            if (empty($arrParam['name'])) {
                return error('缺少参数');
            }
            try {
                CategoryLogic::getInstance()->add($arrParam['name'], $arrParam['pid'], $arrParam['sort']);
            } catch (\Exception $e) {
                return error($e->getMessage());
            }
            return success('已添加');
        } else {
            $arrCategory = CategoryLogic::getInstance()->treeList();
            return view('', ['arrCategory' => $arrCategory]);
        }
    }

    public function edit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $arrParam = $this->request->all();
            if (empty($arrParam['name'])) {
                return error('缺少参数');
            }
            try {
                CategoryLogic::getInstance()->edit($id, $arrParam['name'], $arrParam['pid'], $arrParam['sort']);
            } catch (\Exception $e) {
                return error($e->getMessage());
            }
            return success('已更新');
        } else {
            $arrCategory = CategoryLogic::getInstance()->treeList();
            $arrData = CategoryLogic::getInstance()->getRowById($id);
            return view('', ['arrCategory' => $arrCategory, 'arrData' => $arrData]);
        }
    }

    public function del()
    {
        $id = $this->request->param('id');
        CategoryLogic::getInstance()->del($id);
        return success('已删除');
    }
}